package net.xdclass.online_xdclass.service.impl;

import net.xdclass.online_xdclass.model.entity.User;
import net.xdclass.online_xdclass.mapper.UserMapper;
import net.xdclass.online_xdclass.service.UserService;
import net.xdclass.online_xdclass.utils.CommonUtils;
import net.xdclass.online_xdclass.utils.JWTUtils;
import net.xdclass.online_xdclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public int save(Map<String, String> userInfo) {
        User user = parseToUser(userInfo);
        if (user!=null) {
            return userMapper.save(user);
        }
        return -1;
    }

    private User parseToUser(Map<String, String> userInfo) {
//containsKey是Map中的方法用来判断对应的key值是否存在 成功之后再把值存入User里面
        if (userInfo.containsKey("phone") && userInfo.containsKey("pwd") && userInfo.containsKey("name")) {
            User user = new User();
            user.setName(userInfo.get("name"));
            user.setHeadImg(getRunDomeImg());
            user.setCreateTime(new Date());
            user.setPhone(userInfo.get("phone"));
            String pwd = userInfo.get("pwd");
//            MD5加密

            user.setPwd(CommonUtils.MD5(pwd));
            System.out.println(CommonUtils.MD5(pwd));
            return user;
        }else {
            return null;
        }
    }


    @Override
    public String findByPhoneAndPwd(String phone, String pwd) {


        User user = userMapper.findByPhoneAndPwd(phone, CommonUtils.MD5(pwd));

        if(user == null){
            return null;

        }else {
            String token = JWTUtils.geneJsonWebToken(user);
            return token;
        }
    }

    @Override
    public User findByUserId(Integer userId) {
        return userMapper.findByUserId(userId);
    }

    //    静态属性不可更改
    private static final String [] headImg = {
                "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg",
                "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg",
                "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg",
                "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg",
                "https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"
        };
    /**
     * 产生随机下标  先获取图片的长度获取到下标 然后用随机函数进行下标的随机参数然后返回图片下标
     * @return
     */
    private String getRunDomeImg(){
        int size=headImg.length;
//        Random随机数函数
        Random random=new Random();
        int index=random.nextInt(size);
        return headImg[index];
    }


}
